package org.abratuhi.kvngroupware.scenario.mptua;

import org.abratuhi.kvngroupware.network.AbstractRequestMessageProceeder;
import org.abratuhi.kvngroupware.network.Client;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.scenario.manager.ScenarioManager;
import org.abratuhi.kvngroupware.scenario.model.Scenario;
import org.abratuhi.kvngroupware.server.db.ServerDB;
import org.abratuhi.kvngroupware.user.manager.UserManager;
import org.jdom.Element;

public class ScenarioRequestMessageProceeder extends AbstractRequestMessageProceeder{
	MessageSender sender;
	UserManager usermanager;
	ScenarioManager scenariomanager;
	ServerDB db;

	public ScenarioRequestMessageProceeder(MessageSender sender, UserManager usermanager, ScenarioManager scenariomanager, ServerDB db){
		this.sender = sender;
		this.usermanager = usermanager;
		this.scenariomanager = scenariomanager;
		this.db = db;
	}

	@Override
	public void proceedMessage(Client client, Message message) {
		Element request = message.getRoot().getChild("request");
		String type = request.getAttributeValue("type");
		String action = request.getAttributeValue("action");

		if(type.equals("scenario")){
			String teamId = request.getAttributeValue("teamId");
			String userId = request.getAttributeValue("userId");
			String scenarioId = request.getAttributeValue("scenarioId");
			Scenario s = (request.getChildren().size() > 0) ? Scenario.fromElement(request.getChild("scenario")) : null;

			String[] attrNames = new String[]{"type", "action", "userId", "teamId", "scenarioId", "status"};
			String[] attrValues= new String[]{type, action, userId, teamId, scenarioId, "ok"};
			String text = new String();
			Element[] content = new Element[0];
			Message responseMessage;
			
			if(action.equals("get")){
				content = db.getScenarios(teamId);
			}
			else if(action.equals("create")){
				//content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
				//for(int i=0; i<content.length; i++) kvnserver.getDB().addScenario(content[i]);
				db.addScenario(s.toElement());
				content = new Element[]{s.toElement()};
			}
			else if(action.equals("join")){
				content = new Element[]{s.toElement()};
			}
			else if(action.equals("leave")){
				content = new Element[]{s.toElement()};
			}
			else if(action.equals("update")){
				content = new Element[]{s.toElement()};
				scenariomanager.update(scenarioId, s);
				db.updateScenario(s.toElement());
			}
			else if(action.equals("delete")){
				content = new Element[]{s.toElement()};
				scenariomanager.remove(s.getId());
				db.removeScenario(teamId, scenarioId);
			}

			responseMessage = sender.createMessage(attrNames, attrValues, text, content);
			sender.sendMessage(responseMessage);
		}
	}

}
